package cn.stazxr.core.aspect;

import cn.stazxr.annotation.Log;
import cn.stazxr.entity.YdlOperLog;
import cn.stazxr.service.YdlOperLogService;
import cn.stazxr.utils.WebUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Objects;

/**
 * @author talentestors
 * @version 1.0
 * @since 2025.11.03
 **/
@Component
@Aspect
@Slf4j
public class LogAspect implements BeanFactoryAware {

	//	@Autowired
//	@Qualifier("virtualExecutor")
//	private ExecutorService virtualExecutor;
	@Autowired
	private YdlOperLogService ydlOperLogService;

	private BeanFactory beanFactory;

	@Override
	public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
		this.beanFactory = beanFactory;
	}

	@AfterReturning("@annotation(opLog)")
	public void afterReturning(JoinPoint joinPoint, Log opLog) {
		HttpServletRequest request = Objects.requireNonNull(WebUtils.getCurrentRequest());
//		LogAspect logAspect = beanFactory.getBean(LogAspect.class);
//		logAspect.logHandler(request, joinPoint, opLog, null);
		logHandler(request, joinPoint, opLog, null);
		log.info("{}, 执行了【{}】操作", request.getHeader("userName"), opLog.title());
	}

	@AfterThrowing(value = "@annotation(opLog)", throwing = "exception")
	public void afterThrowing(JoinPoint joinPoint, Log opLog, Exception exception) {
		HttpServletRequest request = Objects.requireNonNull(WebUtils.getCurrentRequest());
//		LogAspect logAspect = beanFactory.getBean(LogAspect.class);
//		logAspect.logHandler(request, joinPoint, opLog, exception);
		logHandler(request, joinPoint, opLog, exception);
		log.error("{}, 执行了【{}】操作: {}", request.getHeader("userName"), opLog.title(), exception.getMessage());
	}

	/**
	 * 执行添加日志的方法
	 */
//	@Async("virtualExecutor")
	public void logHandler(HttpServletRequest request, JoinPoint joinPoint, Log log, Exception exception) {
		// 提交任务
		// 1. 根据现场信息，封装日志实例
		YdlOperLog.YdlOperLogBuilder opLogBuilder = YdlOperLog.builder();
		opLogBuilder.title(log.title())
			.businessType(log.businessType());
		if (exception != null) {
			opLogBuilder.errormsg(exception.getMessage().substring(0, 1000)).status(500);
		} else {
			opLogBuilder.status(200);
		}
		// request 当中获取的一些信息
		YdlOperLog operLog = opLogBuilder.opertime(Instant.now())
			.method(joinPoint.getSignature().getName())
			.operIp(request.getRemoteAddr())
			.requestMethod(request.getMethod())
			.operName(request.getHeader("userName"))
			.operUrl(request.getRequestURI())
			.build();
		// 保存日志对象
		ydlOperLogService.insert(operLog);
	}

//	/**
//	 * 执行添加日志的方法
//	 */
//	private void logHandler(HttpServletRequest request, JoinPoint joinPoint, Log opLog, Exception exception) {
//		// 提交任务
//		// 1. 根据现场信息，封装日志实例
//		YdlOperLog.YdlOperLogBuilder opLogBuilder = YdlOperLog.builder();
//		opLogBuilder.title(opLog.title())
//			.businessType(opLog.businessType());
//		if (exception != null) {
//			opLogBuilder.errormsg(exception.getMessage().substring(0, 1000)).status(500);
//		} else {
//			opLogBuilder.status(200);
//		}
//		// request 当中获取的一些信息
//		YdlOperLog operLog = opLogBuilder.opertime(Instant.now())
//			.method(joinPoint.getSignature().getName())
//			.operIp(request.getRemoteAddr())
//			.requestMethod(request.getMethod())
//			.operName(request.getHeader("userName"))
//			.operUrl(request.getRequestURI())
//			.build();
////		System.out.println("main-------" + Thread.currentThread().getName());
//		// 保存日志对象
//		virtualExecutor.execute(() -> {
////			System.out.println("opLog-------" + Thread.currentThread());
//			ydlOperLogService.insert(operLog);
//		});
//	}

}
